<?php
/**
 * Created by andrei
 * Date: 9/11/12
 * Time: 10:33 AM
 */
class Login extends Engine {

	public static function isLoggedIn() {

		$username = self::$S->Get('login_username');
		$password = self::$S->Get('login_password');

		if (!$username || !$password) {
			$loginPage = Db_Cms_Pages::getLoginPage();
			if (rtrim(get('page'), '/') != $loginPage['p_url']) {
				self::$S->Set('login_redirect_url', '/' . get('page'));
				Utils::redirectTo('/' . $loginPage['p_url']);
			}
		} else {
			if ((time() - self::$S->Get('login_timestamp')) >= self::$S->Get('login_lifetime')) {
				self::$S->Remove();
				$loginPage = Db_Cms_Pages::getLoginPage();
				if (rtrim(get('page'), '/') != $loginPage['p_url']) {
					self::$S->Set('login_redirect_url', '/' . get('page'));
					self::$S->message(t(T_MESSAGE_RESULT, 'login_expired'), true);
					Utils::redirectTo('/' . $loginPage['p_url']);
				}
			}
			if (!(self::$USER = Db_Accounts_Users::getUser($username, $password))) {
				self::$S->Remove();
				$loginPage = Db_Cms_Pages::getLoginPage();
				if (rtrim(get('page'), '/') != $loginPage['p_url']) {
					self::$S->Set('login_redirect_url', '/' . get('page'));
					self::$S->message(t(T_MESSAGE_RESULT, 'no_such_user'), true);
					Utils::redirectTo($loginPage['p_url']);
				}
			} else {
				//get all permissions and define constants
				self::setPermissions();
			}
		}
	}

	/**
	 * @static
	 *
	 */
	private static function setPermissions() {
		if ($permissions = self::$S->Get('user_permissions')) {
			Utils::defineArray($permissions);
		} else {
			$permissions = Db_Accounts_Permissions::getCurrentUserPermissions();

			self::$S->Set('user_permissions', $permissions);
			Utils::defineArray($permissions);
		}
	}


	/**
	 * @static
	 * @param $const
	 * @param bool $redirect
	 * @param string $message
	 * @return bool
	 */
	public static function hasPermission ($const, $redirect = false, $message = '') {
		if (defined('CLI')) {
			return true;
		}
        if (defined($const)) {
            return true;
        } else {
            if ($redirect !== false) {
                if ($redirect === true) {
                    $redirect = '/';
                }
				if (empty($message)) {
					$message = t(T_MESSAGE_RESULT, 'access_denied');
				}
				self::$S->message($message, true);
                Utils::redirectTo($redirect);
				return false;
            } else {
                return false;
            }
        }
    }

}